package com.shanlitech.bluetooth.map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class ImageLoader {
    private static final HashMap<String,Bitmap> mImageCache = new HashMap<>();

    public static Bitmap load(Context context,String img) {
        Bitmap bitmap = mImageCache.get(img);
        if( bitmap != null ) {
            return bitmap;
        }
        try {
            if (img.startsWith("asset://")) {
                int idx = 8;
                while (img.charAt(idx) == '/') {
                    ++idx;
                }
                final String filePath = img.substring(idx);
                InputStream input = context.getAssets().open(filePath);
                bitmap = BitmapFactory.decodeStream(input);
            } else if( img.startsWith("res://") ) {
                int idx = 6;
                while (img.charAt(idx) == '/') {
                    ++idx;
                }
                final String resUri = img.substring(idx);
                final int resId = context.getResources().getIdentifier(resUri,null,null);
                if( resId > 0 ) {
                    bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
                }
            } else {
                InputStream input = context.getContentResolver().openInputStream(Uri.parse(img));
                bitmap = BitmapFactory.decodeStream(input);
            }

        } catch( IOException ex ) {
            ex.printStackTrace();
        }
        if( bitmap != null ) {
            mImageCache.put(img, bitmap);
        }
        return bitmap;
    }
}
